package org.summerframework.component.security.oauth.wechat;

import com.alibaba.fastjson.JSONObject;
import org.summerframework.component.httpclient.HttpParam;
import org.summerframework.component.security.oauth.LoginType;
import org.summerframework.component.security.oauth.OAuthAppIdAndAppSecret;
import org.summerframework.component.security.oauth.OAuthResultCode;
import org.summerframework.component.security.oauth.exception.WeCatException;
import org.summerframework.component.security.oauth.util.HttpClientFinshUtil;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * WeChatOAuthSupper
 *
 * @author 石超
 * @date 2016/3/25
 */
public class WechatMiniAppsOAuthSupper implements WechatMiniAppsOAuthInterceptor {
    //获取用户个人信息
    private static final String userInfoUrl = "https://api.weixin.qq.com/sns/jscode2session";

    private final WechatMiniAppsAppIdAndAppSecret wechatMiniAppsAppIdAndAppSecret;

    public WechatMiniAppsOAuthSupper(WechatMiniAppsAppIdAndAppSecret wechatMiniAppsAppIdAndAppSecret) {
        this.wechatMiniAppsAppIdAndAppSecret = wechatMiniAppsAppIdAndAppSecret;
    }

    @Override
    public WechatUserInfo getResultInfo(WechatAccessToken wechatAccessToken) {
        WechatUserInfo resultInfo = new WechatUserInfo();
        resultInfo.setAccessToken(wechatAccessToken.getCode());
        return resultInfo;
    }

    @Override
    public WechatUserInfo getInfo(WechatUserInfo wechatUserInfo) {
        HttpParam httpParam = new HttpParam();
        httpParam.setMethod(RequestMethod.POST);
        httpParam.setUrl(userInfoUrl);
        httpParam.addParam("appid", wechatMiniAppsAppIdAndAppSecret.getAppId());
        httpParam.addParam("secret", wechatMiniAppsAppIdAndAppSecret.getAppSecret());
        httpParam.addParam("js_code", wechatUserInfo.getAccessToken());
        JSONObject json = HttpClientFinshUtil.finsh(httpParam, "utf8");
        //判断是否有错
        if (json.containsKey("errcode")) {
            Integer errcode = json.getInteger("errcode");
            String errmsg = json.getString("errmsg");
            throw new WeCatException(OAuthResultCode.ILLEGAL_ARGUMENT, errcode + ": " + errmsg);
        }
        //用户的信息
        String openid = json.getString("openid");
        String unionid = json.getString("unionid");
        String session_key = json.getString("session_key");
        wechatUserInfo.setOpenid(openid);
        wechatUserInfo.setUnionid(unionid);
        wechatUserInfo.setSessionKey(session_key);
        return wechatUserInfo;
    }

    @Override
    public OAuthAppIdAndAppSecret getOAuthInfo() {
        return wechatMiniAppsAppIdAndAppSecret;
    }

    @Override
    public WechatAccessToken getAccessToken(String code) {
        return new WechatAccessToken(code);
    }

    @Override
    public boolean supportsType(LoginType loginType) {
        return LoginType.WECHAT_MINI_APPS == loginType;
    }
}
